import http from "@/utils/request";
import { defineStore } from "pinia";
import {Categoryitem,ApiRes, TopCategory, SubCategory}from '@/types/index'
//引用常量文件夹的文件,使用默认数据,处理了第一次加载时页面不会没有数据的问题
import {topCategory}from '../constants'
const defaultCategory=topCategory.map(item=>({name:item}))
// interface Categoryitem{
//     id:string
//     name:string
//     picture:string
// }
// interface ApiRes<T>{
//     code:string
//     msg:string
//     result:T[]
// }
export default defineStore('category',{
    state() {
        return {
         list:defaultCategory as Categoryitem[],
         topCategory: {} as TopCategory,
         subCategory: {} as SubCategory,
        }
    },
    actions:{
   async getAllCategory(){
    const res=await http.get<ApiRes<Categoryitem[]>>('/home/category/head')
    this.list=res.data.result
    //给每个一级分类添加一个open属性,用于控制显示隐藏
    res.data.result.forEach(item=>{
        item.open=false
    })
    
   },
   async getTopCategory(id:string){
    const res=await http.get<ApiRes<TopCategory>>('/category',{
        params:{
            id
        }
    })
    this.topCategory=res.data.result 
   },
   async getSubCategory(id:string){
    const res=await http.get<ApiRes<SubCategory>>('/category/sub/filter',{
        params:{
            id
        }
    })
    this.subCategory=res.data.result 
   },
   show(id:string){
    const category=this.list.find(item=>item.id===id)
    //!.强制赋值open属性
    category!.open=true
   },
   hide(id:string){
    const category=this.list.find(item=>item.id===id)
    category!.open=false    
   },
   resetSubCategory() {
    this.subCategory = {} as SubCategory
  }

    },
    getters:{

    }
})